﻿using AVCUMPlatform.BLL.Interface;
using AVCUMPlatform.BLL;
using AVCUMPlatform.Entities;
using Microsoft.AspNetCore.Mvc;
using AVCUMPlatform.HelperLibrary;

namespace AVCUMPlatform.Controllers
{
    /// <summary>
    /// 认证接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class AuthenticationController : ControllerBase
    {
        private ISourceBLL _sourceBLL = BLLContainer.Resolve<ISourceBLL>();

        /// <summary>
        /// 获取应用的access_token
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NoNeedLogin]
        public ActionResult GetToken(AuthenticationReq authentication)
        {
            try
            {
                var sourceObj = _sourceBLL.GetAll().FirstOrDefault(x => x.AK == authentication.AK && x.SK == authentication.SK);
                if (sourceObj == null || sourceObj.Id <= 0)
                {
                    return new JsonResult(new { code = -1, data = "", msg = "授权码不存在" });
                }
                string token = Util.MD5Encrypt32(authentication.AK + authentication.SK);
                if (AuthorizationFilter.Get<Source>(token) == null)
                {
                    AuthorizationFilter.Set(token, sourceObj, TimeSpan.FromDays(1));
                }
                return new JsonResult(new { code = 1, data = token, msg = "认证成功" });
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
                return new JsonResult(new { code = -2, data = "", msg = "认证授权异常" });
            }
        }
    }
}
